/**
 * 创建者：luyiming
 * 该页面用于：
 * 创建时间： 2020-03-06 21:46:01
 */
import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // 分页
import ReportTable from "@/components/luyiming/ReportTable/index.vue";
import { getEnterpriseDeclareLst, getDeclareDeviceDate, getReport, entDetial, InsertDeclare } from "@/api/RCIM/RCIM-source";
import { cloneDeep } from "lodash";
import { validInt } from "@/utils/validate";
import moment from "moment";
export default {
	name: 'RcimSourceDeclaration_view',
	components: {
		Table,
		Pagination,
		ReportTable,
	},
	// 数据
	data() {
		return {
			info: DECLARATION_CONTACT_INFO,
			tableData: [],
			tableHead: [{
					prop: "registrant",
					label: "登记人",
					width: "",
					align: "center"
				},
				{
					prop: "leadingCadre",
					label: "企业负责人",
					width: "",
					align: "center"
				},
				{
					prop: "reportingTime",
					label: "申报时间",
					width: "",
					align: "center"
				},
				{
					prop: "operate",
					label: "操作",
					width: "",
					align: "center"
				}
			],
			listLoading: false,
			total: 0,
			listQuery: {
				page: 1,
				limit: 10,
				type: '1'
			},
			dialogFormVisible: false,
			timeParam: [
				moment().subtract(1, 'months').format('YYYY-MM-DD'),
				moment().format('YYYY-MM-DD')
			],
			reportTable: [
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '企业名称',
						key: 'name',
						disable: true,
					}]
				},
				{
					col: [{
						fspan: 12,
						span: [12, 12],
						name: '登记人：',
						key: 'registrant',
						disable: true,
					},{
						fspan: 12,
						span: [12, 12],
						name: '企业负责人：',
						key: 'chargePerson',
						disable: true,
					}]
				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '申报日期：',
						key: 'declareTime',
						formType: 'select',
						formTypeC: 'option',
						required: true,
						options: [
							{
								label: '2020-2-2',
								value: '2020-2-2'
							}
						]
					}]

				},
			],
			sorceReport: [
				{
					col: [{
						fspan: 24,
						span: [24, 0],
						name: '放射源（单位/枚）',
						key: null,
					}]
				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '备案源数',
						key: 'sourceNum',
						disable: true,
					}]

				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '在用源数',
						required: true,
						key: 'useSourceNum'
					}]

				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '在库源数',
						required: true,
						key: 'stockSourceNum'
					}]

				},
			],
			deviceReport: [
				{
					col: [{
						fspan: 24,
						span: [24, 0],
						name: '射线装置（单位/台）',
						key: null
					}]
				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '在用台数',
						required: true,
						key: 'useDeviceNum'
					}]

				},
			],
			// 源验证规则
			sourceRule: {
				useSourceNum: [
					{required: true, message: '请输入放射源在用源数'},
					{validator: validInt,  message: '放射源在用源数必须为整数'}
				],
				stockSourceNum: [
					{required: true, message: '请输入放射源在库源数'},
					{validator: validInt,  message: '放射源在库源数必须为整数'}
				],
				declareTime: [
					{required: true, message: '请选择放射源申报日期'}
				]
			},
			// 设备验证规则
			deviceRule: {
				useDeviceNum: [
					{required: true, message: '请输入射线装置在用源数'},
					{validator: validInt,  message: '射线装置在用源数必须为整数'}
				],
				declareTime: [
					{required: true, message: '请选择射线装置申报日期'}
				]
			},
			sourceForm:[],
			deviceForm:[],
			reportSourceTitle: "放射源每日检查登记申报台账",
			reportDeviceTitle: "射线装置每周检查登记申报台账",
			isShowSourceReport: false,
			isShowDeviceReport: false,
			entData: null,
			isReadOnly: false,
			editId: '',
		}
	},
	// 监听
	watch: {
		'listQuery.type'() {
			Object.assign(this.listQuery, {
				page: 1,
				limit: 10
			})
			// console.log(this.listQuery);

			this.getList()
		}
	},
	// Vue实例初始化完成
	created() {
		this.sourceForm = cloneDeep(this.reportTable);
		this.sourceForm.splice(1,0,...cloneDeep(this.sorceReport));
		this.deviceForm = cloneDeep(this.reportTable);
		this.deviceForm.splice(1,0,...cloneDeep(this.deviceReport));
	},
	// Vue挂载完成
	mounted() {
		this.search()
		this.entData = this.entInfo()
	},
	// Vue实例销毁前
	beforeDestroy() {

	},
	// 挂载的方法
	methods: {
		/**
		 * 查询数据
		 */
		search() {
			if(this.timeParam.length !== 0){
				this.listQuery.startTime = moment(this.timeParam[0]).format('YYYY-MM-DD')
				this.listQuery.endTime = moment(this.timeParam[1]).format('YYYY-MM-DD')
			}
			this.getList()
		},
		/**
		 * 打开弹窗
		 */
		openDialog() {
			this.dialogFormVisible = true
		},
        /**
         * @desc 调用接口获取企业信息
         */
		entInfo(){
			return entDetial({}).then(res => {
				return res?.data?.entData ?? {}
			})
		},
        /**
         * @desc 新增报表
         */
		async addReport(){
			this.openDialog();
			this.isReadOnly = false;
			getDeclareDeviceDate({}).then(res => {
				// debugger
				if(res.data.sourceDate) {
					this.isShowSourceReport = true;
				const sourceForm = cloneDeep(this.reportTable);
				sourceForm[sourceForm.length - 1].col[0].options = res.data.sourceDate.map(item => {
					return {
						lable: item.time,
						value: item.time,
						disable: item.status === 0
					}
				})
				sourceForm.splice(1,0,...cloneDeep(this.sorceReport));
				this.sourceForm = sourceForm;
				}
				if(res.data.deviceDate) {
					this.isShowDeviceReport = true;
					const deviceForm = cloneDeep(this.reportTable);
					deviceForm[deviceForm.length - 1].col[0].options = res.data.deviceDate.map(item => {
						return {
							lable: item.time,
							value: item.time,
							disable: item.status === 0
						}
					})
					deviceForm.splice(1,0,...cloneDeep(this.deviceReport));
					this.deviceForm = deviceForm;
				}
				if(!this.isShowSourceReport && !this.isShowDeviceReport){
					this.dialogFormVisible = false;
					return this.$message.warning('您没有放射源和射线装置需要申报')
				}
				this.$nextTick(() => {
					// 赋值
					this.entData.then(res => {
						if(this.isShowSourceReport){
							// console.log(this.$refs.reportSource, this.$refs.reportSource.setDefaultValue)
							this.$refs.reportSource.setDefaultValue(res)
						}
						if(this.isShowDeviceReport){
							this.$refs.reportDevice.setDefaultValue(res)
						}
					})
				})
			})
		},
        /**
         * @desc 获取表格数据
         */
		getList(){
			this.listLoading = true;
			getEnterpriseDeclareLst(
				this.listQuery
			).then(res => {
				this.listLoading = false;
				this.total = res.data.total;
				this.tableData = res.data.delarationList;
			})
		},
        /**
         * @desc 关闭详情
         */
		handleClose(){
			this.isShowDeviceReport = false;
			this.isShowSourceReport = false;
			this.dialogFormVisible = false;
			this.editId = '';
		},
        /**
         * @desc 提交报表
         */
		async submitReport(){
			const formSource = this.$refs.reportSource?.submitTable() || false;
			const formDevice = this.$refs.reportDevice?.submitTable() || false;
			const sourceNeed = ['stockSourceNum','useSourceNum', 'declareTime']
			const deviceNeed = ['useDeviceNum', 'declareTime']
			let isNeedsourceNeedValit = true;
			let isNeeddeviceNeedValit = true;
			// 当放射源存在且设备不存在
			if(formSource && !formDevice) {
				isNeeddeviceNeedValit = false
			}
			// 当放射源不存在且设备存在
			if(!formSource && formDevice) {
				isNeedsourceNeedValit = false;
			}
			if(formSource && formDevice){
				if(!formSource.stockSourceNum && !formSource.useSourceNum && !formSource.declareTime){
					isNeedsourceNeedValit = false;
				}
				if(!formDevice.useDeviceNum && !formDevice.declareTime){
					isNeeddeviceNeedValit = false;
				}
			}
			if(!isNeeddeviceNeedValit && !isNeedsourceNeedValit){
				isNeedsourceNeedValit = true;
			}
			// console.log('form', formSource, formDevice)
			const needKeys = {
				// id: '',
			}
			if(this.editId) needKeys.id = this.editId;
			let sucesSource = true;
			let sucesDevice = true;
			let issucesSourceGo = true;
			let issucesDeviceGo = true;
			// 如果需要校验放射源
			if(isNeedsourceNeedValit){
				issucesSourceGo = await this.$refs.reportSource?.validForm(formSource, this.sourceRule).then(valid => valid);
			}
			// 如果需要校验射线装置
			if(isNeeddeviceNeedValit){
				// 如果放射源校验没通过且要校验射线装置
				if(!issucesSourceGo){
					return
				}
				// 如果放射源校验通过且校验射线装置
				issucesDeviceGo = await this.$refs.reportDevice?.validForm(formDevice, this.deviceRule).then(valid => valid);
			}
			// 如果两个都校验通过了
			if(issucesSourceGo && issucesDeviceGo){
				if(isNeedsourceNeedValit){
					const submit = {
						type: '1'
					}
					sourceNeed.forEach(itemNeedKey => {
						submit[itemNeedKey] = formSource[itemNeedKey]
					})
					Object.assign(submit, needKeys)
					await InsertDeclare(submit).then(res => {
						if(res.code === 200){
							this.getList()
							return this.$message.success('放射源申报成功');
						}
						throw new Error('放射源申报失败')
					}).catch(error => {
						sucesSource = false
						this.$message.error(error)
					})
				}

				if(isNeeddeviceNeedValit){
					const submit = {
						type: '0'
					}
					deviceNeed.forEach(itemNeedKey => {
						submit[itemNeedKey] = formDevice[itemNeedKey]
					})
					Object.assign(submit, needKeys)
					await InsertDeclare(submit).then(res => {
						if(res.code === 200){
							this.getList()
							return this.$message.success('射线装置申报成功')
						}
						throw new Error('射线装置申报失败')
					}).catch(error => {
						sucesDevice = false
						this.$message.error(error)
					})
				}
			}else{
				return
			}
			// if(isNeedsourceNeedValit){
			// 	// 调用组件验证方法
			// 	issucesSourceGo = await this.$refs.reportSource?.validForm(formSource, this.sourceRule).then(async valid => {
			// 		if(valid) {
						// const submit = {
						// 	type: '1'
						// }
						// sourceNeed.forEach(itemNeedKey => {
						// 	submit[itemNeedKey] = formSource[itemNeedKey]
						// })
						// Object.assign(submit, needKeys)
						// await InsertDeclare(submit).then(res => {
						// 	if(res.code === 200){
						// 		this.getList()
						// 		return this.$message.success('放射源申报成功');
						// 	}
						// 	throw new Error('射线装置申报失败')
						// }).catch(error => {
						// 	sucesSource = false
						// 	this.$message.error(error)
						// })
			// 		} else {
			// 			sucesSource = false
			// 		}
			// 		return valid
			// 	})

			// }
			// if(isNeeddeviceNeedValit){
			// 	if(!issucesSourceGo){
			// 		return
			// 	}
			// 	// 调用组件验证方法
			// 	this.$refs.reportDevice?.validForm(formDevice, this.deviceRule).then(async valid => {
			// 		if(valid) {
			// 			const submit = {
			// 				type: '0'
			// 			}
			// 			deviceNeed.forEach(itemNeedKey => {
			// 				submit[itemNeedKey] = formDevice[itemNeedKey]
			// 			})
			// 			Object.assign(submit, needKeys)
			// 			await InsertDeclare(submit).then(res => {
			// 				if(res.code === 200){
			// 					this.getList()
			// 					return this.$message.success('射线装置申报成功')
			// 				}
			// 				throw new Error('射线装置申报失败')
			// 			}).catch(error => {
			// 				sucesDevice = false
			// 				this.$message.error(error)
			// 			})
			// 		} else {
			// 			sucesDevice = false
			// 		}
			// 	})
			// }
			setTimeout(() => {
				if(sucesSource && sucesDevice){
					this.handleClose();
				}
			},1000)
		},
        /**
         * @desc 查看表格单数据详情方法
         */
		setDetial(row){
			this.editId = row.id;
			getReport({
				id: row.id,
				type: this.listQuery.type === '1' ?  1 : 0
			}).then(res => {
				const report = cloneDeep(this.reportTable);
				report.splice(2,1,{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '申报日期：',
						key: 'declareTime',
						formType: 'select',
						formTypeC: 'option',
						disable: true,
						options: []
					}]
				});
				if(res.data.deviceData){
					this.isShowDeviceReport = true;
					report.splice(1,0,...cloneDeep(this.deviceReport));
					this.deviceForm = report;
				}
				if(res.data.sourceData){
					this.isShowSourceReport = true;
					report.splice(1,0,...cloneDeep(this.sorceReport));
					this.sourceForm = report;
				}
				this.entData.then(resEnt => {
					if(this.isShowSourceReport){
						this.$refs.reportSource.setDefaultValue(Object.assign({}, resEnt, res.data.sourceData))
					}
					if(this.isShowDeviceReport){
						this.$refs.reportDevice.setDefaultValue(Object.assign({}, resEnt, res.data.deviceData))
					}
				})
			})
		},
        /**
         * @desc 查看表格单数据详情、不可编辑
         */
		handleFind(row){
			this.openDialog()
			this.isReadOnly = true;
			this.setDetial(row)
		},
        /**
         * @desc 查看表格单数据详情、可编辑
         */
		handleEdit(row){
			this.openDialog();
			this.isReadOnly = false;
			this.setDetial(row);
		}
	},
}
